package com.fjnu.service.impl;

import com.fjnu.dao.UserDao;
import com.fjnu.dto.UserConditionDto;
import com.fjnu.entity.User;
import com.fjnu.service.UserService;
import com.fjnu.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public User queryByName(String username) {
        if (username == null || username.trim().isEmpty()) {
            return null;
        }
        UserConditionDto condition = new UserConditionDto();
        condition.setUsername(username);
        List<User> users = userDao.selectByCondition(condition);
        return users != null && !users.isEmpty() ? users.get(0) : null;
    }
    @Override
    public int register(User user) {
        if (user == null || user.getName() == null || user.getPassword() == null) {
            return 0;
        }
        // 检查用户名是否已存在
        User existingUser = queryByName(user.getName());
        if (existingUser != null) {
            return 0; // 用户名已存在
        }
        return userDao.insert(user);
    }

    @Override
    public PageResult<User> queryUsers(UserConditionDto userCondition, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum < 1) pageNum = 1;
        if (pageSize == null || pageSize < 1) pageSize = 10;

        List<User> allUsers = userDao.selectByCondition(userCondition);
        if (allUsers == null || allUsers.isEmpty()) {
            return new PageResult<>(pageNum, pageSize, 0L, null);
        }

        // 内存分页（简化实现，生产环境应在SQL中分页）
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, allUsers.size());

        if (startIndex >= allUsers.size()) {
            return new PageResult<>(pageNum, pageSize, (long) allUsers.size(), null);
        }

        List<User> pageData = allUsers.subList(startIndex, endIndex);
        return new PageResult<>(pageNum, pageSize, (long) allUsers.size(), pageData);
    }

    @Override
    public void addAssignRole(String userId, List<Integer> roleIds) {
        if (userId == null || roleIds == null || roleIds.isEmpty()) {
            return;
        }

        Integer userIdInt = Integer.parseInt(userId);
        userDao.batchInsertUserRoles(userIdInt, roleIds);
    }
}